from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from datetime import date, timedelta

from apps.users.models import User
from apps.goods.models import GoodsVisitCount
# 序列化器
from apps.meiduo_admin.serializers.home import UserCategoryCountSerializer


class UserTotalCountView(APIView):
    """用户总量"""
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):

        count = User.objects.all().count()

        return Response({'count': count})


class UserDailyCountView(GenericAPIView):
    """日增用户总量"""
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):

        now_date = date.today()

        count = User.objects.filter(date_joined__gte=now_date).count()

        return Response({'count': count})


class UserDailyActiveCountView(GenericAPIView):
    """日活跃用户统计"""
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):

        now_date = date.today()

        count = User.objects.filter(last_login__gte=now_date).count()

        return Response({'count': count})


class UserDailyOrderCountView(GenericAPIView):
    """日下单用户量"""
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):

        now_date = date.today()

        count = User.objects.filter(orderinfo__create_time__gte=now_date).count()

        return Response({'count': count})


class UserMonthCountView(APIView):
    """月增用户量"""
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):

        # 获取前30天时间，需要知道当前时间
        today = date.today()

        # 获取30天前的日期
        start_date = today - timedelta(days=30)

        # 准备用户月新增列表
        user_count_list = []

        # 获取每一天的时间段,遍历每一天
        for i in range(31):
            # 每天的开始时间
            begin_time = start_date + timedelta(days=i)
            # 每天的结束时间
            end_time = start_date + timedelta(days=(i + 1))

            # 根据日期查询新增用户， 新增日期大于等于当前时间，小于后一天时间
            count = User.objects.filter(date_joined__gte=begin_time, date_joined__lt=end_time).count()
            # 把获取到的数据添加到列表中
            user_count_list.append({
                'count': count,
                'date': begin_time
            })

        # 返回列表
        return Response(user_count_list)


class UserCategoryCountAPIView(APIView):
    """日分类商品访问量"""

    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):

        # 获取当天时间
        today = date.today()
        # 查询数据
        goods = GoodsVisitCount.objects.filter(date__gte=today)
        # 把对象查询集转换为字典
        serializer = UserCategoryCountSerializer(instance=goods, many=True)
        # 返回JSON数据
        return Response(serializer.data)